package depthtag;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import depthtag.display.Viewer;
import depthtag.filter.GeneralFileFilter;


public class PictureParser {
	String folder;
	List<Date> timestamps;
	ExifToolWrapper etw;
	
	public static final String CREATED_DATE = "CreateDate";
	public static final String GPS_ALTITUDE = "GPSAltitude";
	public static final String GPS_ALTITUDE_REF = "GPSAltitudeRef";
	public static final String BELOW_SEA_LEVEL = "1";
	public static final String XMP_SUBJECT = "XMP:Subject>";
	public PictureParser(String pathToExifTool, String folder) throws FileNotFoundException {
		this.folder = folder;
		etw = new ExifToolWrapper(new File(pathToExifTool));
	}
	
	public Map<File,Map<String,String>> getTimestamps(Viewer callback ){
		FilenameFilter filter = new GeneralFileFilter(callback.getFileNameExtension());
		HashSet<String> tagNames = new HashSet<String>();
		tagNames.add(CREATED_DATE);
		File rootFolder = new File(folder);
		if(rootFolder.isDirectory()){
			
			File[] files = rootFolder.listFiles(filter);
			if(files != null){
				Map<File,Map<String,String>> result = etw.getTagsFromFiles(Arrays.asList(files), tagNames);
				if(result != null){
					if(result.size() == 0 ){
						callback.addStatusText("Did not find any files with selected extension");
					}
					else{
						for (Entry<File,Map<String,String>> file : result.entrySet()) {
							String createdDate = file.getValue().get(CREATED_DATE);
							callback.addStatusText("Found " + file.getKey().getName() + " create date=" + createdDate);
						}
					}
					return result;
				}
			}
		}
		return null;
	}
	
	public void addDepthToImage(File file, Double depth, boolean noCopy, boolean metric){
		Map<String,String> map = new HashMap<String, String>();
		map.put(GPS_ALTITUDE_REF, BELOW_SEA_LEVEL);
		map.put(GPS_ALTITUDE, depth.toString());
		DecimalFormat twoDForm = new DecimalFormat("####.#", new DecimalFormatSymbols(java.util.Locale.US));
		if(metric){
			double roundedDepth = Double.valueOf(twoDForm.format(depth));
			map.put(XMP_SUBJECT, "Depth:" + roundedDepth + " meter" );			
		}
		else{
			double depthInFeet = Double.valueOf(twoDForm.format(depth * 3.2808399));
			map.put(XMP_SUBJECT, "Depth:" + depthInFeet + " feet" );
		}
//		System.out.println("Saving " + file.getName() + " with depth " + depth);
		etw.setTagsToFile(file, map, noCopy);
	}	
}





